package com.wgo.bpot.common.transport.util;

import java.net.MalformedURLException;
import java.net.URL;


import com.caucho.hessian.client.HessianProxyFactory;
import com.wgo.bpot.common.transport.exception.db.DatabaseException;
import com.wgo.bpot.common.transport.servicefacade.LightService;
import com.wgo.bpot.common.transport.servicefacade.ServiceFactory;
import com.wgo.bpot.common.transport.servicefacade.hessian.EnumSerializerFactory;
import com.wgo.bpot.common.transport.servicefacade.hessian.MethodSerializerFactory;
import com.wgo.bpot.common.transport.servicefacade.hessian.TransientTypeSerializerFactory;
import com.wgo.bpot.common.transport.servicefacade.hessian.UrlSerializerFactory;
/**
 * Used to create proxy of the remote service.
 * 
 * @author petterei
 * @version $Id: HessianServiceFactory.java,v 1.1 2006-01-27 07:47:44 oranvik Exp $
 * TODO  This class should be moved into a separate module 
 */
public class HessianServiceFactory implements ServiceFactory {
	
	@SuppressWarnings("unchecked")
	public LightService createService(URL remoteUrl) {
		Assert.<URL>assertNotNull(remoteUrl);
		LightService service = null;
		HessianProxyFactory hessianFactory = new HessianProxyFactory();
		hessianFactory.getSerializerFactory().addFactory(new EnumSerializerFactory());
		hessianFactory.getSerializerFactory().addFactory(new MethodSerializerFactory());
		hessianFactory.getSerializerFactory().addFactory(new TransientTypeSerializerFactory());
		hessianFactory.getSerializerFactory().addFactory(new UrlSerializerFactory());
		try {
			hessianFactory.getRemoteResolver();
		} catch (RuntimeException e1) {
			throw new DatabaseException("Could not connect to server, please check server adress.", e1);
		}
		try {
			service = (LightService) hessianFactory.create(LightService.class, remoteUrl.toExternalForm());
		} catch (MalformedURLException e) {
			throw new DatabaseException("Malformed URL", e);
		}
		return service;
	}
	
}
